<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理用户</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/font-awesome.min.css') }}">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 10px;
            text-align: left;
            border: 1px solid #ddd;
        }
        th {
            background-color: #007bff;
            color: white;
        }
        input[type="text"], input[type="password"], select {
            width: 100%;
            padding: 10px;
            margin: 10px -10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            padding: 10px 15px;
            background-color: #007bff;
            border: none;
            color: white;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .alert {
            color: green;
            text-align: center;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0,0,0);
            background-color: rgba(0,0,0,0.4);
            padding-top: 60px;
        }
        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
        }
    </style>
</head>
<body>
    <h1>用户管理</h1>
    <div style="width: 80%;margin: 0 auto;">
        <table id="userTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>角色</th>
                    <th>Email</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
        <button onclick="document.getElementById('addUserModal').style.display='block'">添加用户</button>
        <p>
            <a href="/logout">Logout</a>
        </p>
    </div>

    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <span onclick="document.getElementById('addUserModal').style.display='none'" style="float:right;cursor:pointer;">&times;</span>
            <h2>添加用户</h2>
            <form id="addUserForm" onsubmit="return false;">
                <input type="text" id="username" name="username" placeholder="用户名" required>
                <input type="password" id="password" name="password" placeholder="密码" required>
                <select id="role" name="role">
                    <option value="admin">管理员</option>
                    <option value="employee">普通职工</option>
                </select>
                <input type="text" id="email" name="email" placeholder="email" required>
                <button id="btnAdd" onclick="addUser()">添加</button>
            </form>
        </div>
    </div>

    <script>
        window.onload = function() {
            reloadTableData();
        };
        
        function reloadTableData() {
            fetch('/admin/manage_users')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不是OK');
                    }
                    return response.json();
                })
                .then(data => {
                    const tableBody = document.getElementById('userTable').getElementsByTagName('tbody')[0];
                    tableBody.innerHTML = ''; // 清空表格内容

                    // 遍历返回的数据并填充表格
                    data.forEach(user => {
                        const row = tableBody.insertRow();
                        row.insertCell(0).textContent = user.id;
                        row.insertCell(1).textContent = user.username;
                        row.insertCell(2).textContent = user.password;
                        row.insertCell(3).textContent = user.role;
                        row.insertCell(4).textContent = user.email;
                        if(user.role!='admin') {
                            row.insertCell(5).innerHTML = '<button onclick="deleteUser('+user.id+')">删除</button>';    
                        }
                    });
                })
                .catch(error => {
                    console.error('请求用户数据时出错:', error);
                });
        }

        function addUser() {
            const newUser = {
                username: document.getElementById('username').value,
                password: document.getElementById('password').value,
                role: document.getElementById('role').value,
                email: document.getElementById('email').value
            };

            fetch('/admin/add_user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(newUser)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加用户失败');
                }
                return response.json();
            })
            .then(data => {
                alert(data.message);
                reloadTableData();
                document.getElementById('addUserForm').reset();
                document.getElementById('addUserModal').style.display='none';
            })
            .catch(error => {
                console.error('添加用户出错:', error);
            });
        }

        function deleteUser(userId) {
            if (confirm("确定要删除该用户吗？")) {
                fetch(`/admin/delete_user`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: userId
                    })
                }).then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                }).then(data => {
                    alert(data.message);
                    reloadTableData();
                }).catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
            }
        }
    </script>
</body>
</html>
